﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace SweetSQL.Data.Providers
{
    internal sealed class OleDbConnectionProvider : ConnectionProviderBase
    {
        public OleDbConnectionProvider(ConnectionParameters parameters)
            : base(parameters)
        { }

        public override void Connect()
        {
            if (!Connected)
            {
                StringBuilder builder = new StringBuilder("Data Source=");
                builder.Append(Parameters.DataSource);
                if (!string.IsNullOrEmpty(Parameters.Database))
                {
                    builder.Append(";Initial Catalog=");
                    builder.Append(Parameters.Database);
                }
                if (!string.IsNullOrEmpty(Parameters.Username))
                {
                    builder.Append(";User ID=");
                    builder.Append(Parameters.Username);
                }
                if (!string.IsNullOrEmpty(Parameters.Password))
                {
                    builder.Append(";Password=");
                    builder.Append(Parameters.Password);
                }
                if (!string.IsNullOrEmpty(Parameters.Provider))
                {
                    builder.Append(";Provider=");
                    builder.Append(Parameters.Provider);
                }
                Util.AppendCustomProperties(builder, Parameters.CustomProperties);

                Connection = new OleDbConnection(builder.ToString());
                Connection.Open();
                Connected = true;
            }
        }

        public override IDbCommand CreateCommand(string sql)
        {
            return new OleDbCommand(sql, Connection as OleDbConnection, Transaction as OleDbTransaction) { CommandTimeout = CommandTimeout };
        }

        public override IDataParameter CreateParameter(string name, Type type, int index)
        {
            return new OleDbParameter(name, null);
        }
    }
}
